<template>
  <div>
    <el-dialog
      title="状态回退"
      :visible.sync="dialogVisible"
      width="640px"
      :modal-append-to-body="false"
      @close="closeDialog"
      :close-on-click-modal="false"
      custom-class="brand-dialog-min-width"
      :append-to-body="true"
    >
      <el-form
        class="el-form1 mrT8"
        :model="formData"
        ref="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="操作人：" prop="operator">
          <el-input
            v-model="formData.operator"
            placeholder="请输入"
            @blur="formData.operator = changeValue($event)"
            class="dialogSingleInp"
            maxlength="8"
          ></el-input>
        </el-form-item>
        <el-form-item label="操作原因：" prop="operateReason">
          <el-input
            type="textarea"
            v-model="formData.operateReason"
            autocomplete="off"
            placeholder="请输入操作原因"
            maxlength="200"
            show-word-limit
            class="dialogSingleInp"
            rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="操作凭证："
          prop="operateVoucher"
          v-model="formData.fileJson"
        >
          <!-- <div class="uploadBox">
                <el-button round class="uploadImg">上传</el-button>
                <div class="upLoadDom">
                    <form id="salaryExcelForm">
                        <input type="file" id="salaryExcel" name="file" @change="fileChange" />
                    </form>
                </div>
            </div> -->
          <uploadAnnex
            :limitationFactor="limitationFactor"
            @getFile="getFile"
            :upLoadFile="uploadFile"
          />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <uploadResult
              style="margin-left: 116px !important"
              :resultList="uploadFile"
              @callBackResult="getFile"
            />
          </el-col>
        </el-row>
        <!-- <el-row>
            <el-col :span="24" v-model="formData.fileJson">
              <ul class="clearfix imgStyle">
                <li class="fl" v-for="(item,index) of uploadFile" :key="index">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="item.url"
                    :preview-src-list="srcList"
                    @click="enlargeImg(index)"
                  ></el-image>
                  <i class="icon iconfont iconjian" @click="delFile(index)"></i>
                </li>
              </ul>
            </el-col>
          </el-row> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" class="cancel">取 消</el-button>
        <el-button
          type="primary"
          @click="onSave"
          :loading="isSaveLoading"
          class="save"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import common from '../../kits/common'

export default {
  name: 'statusFallback',
  data() {
    var operateVoucherValid = (rule, value, callback) => {
      if (this.uploadFile.length == 0) {
        return callback(new Error('操作凭证不能为空'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        operator: '',
        operateReason: '',
        upLoadFileAcc: [],
        fileJson: [],
      },
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 5, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeOne', //自定义上传格式校验类型
        messagetip: '要求格式为png，jpg，jpeg格式，附件大小不超过5M', //自定义报错提示语
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        methodTip:
          '请上传操作凭证，附件格式支持png，jpg，jpeg，最多上传5个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
        messageFileSizetip: '最多能上传5M以内的附件',
      },
      srcList: [],
      oldSrcList: [],
      uploadFile: [],
      rules: {
        operator: [
          {
            required: true,
            message: '只能输入汉字',
            trigger: 'blur',
            max: 8,
            pattern: /^[\u4e00-\u9fa5]+$/,
          },
        ],
        operateReason: [
          { required: true, message: '操作原因不能为空', trigger: 'blur' },
        ],
        operateVoucher: [
          { required: true, validator: operateVoucherValid, trigger: 'blur' },
        ],
      },
      isSaveLoading: false,
    }
  },
  created() {},
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    salaryId: String,
  },
  methods: {
    getFile(val) {
      this.uploadFile = val
    },
    closeDialog() {
      this.srcList = []
      this.oldSrcList = []
      this.uploadFile = []
      this.$emit('closeDialogVisible', false)
      this.$refs.formData.resetFields()
    },
    // 状态回退保存
    onSave() {
      this.isSaveLoading = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.formData.fileJson = JSON.stringify(this.uploadFile)
          this.formData.salaryId = this.salaryId
          this.saveFormInfo()
        } else {
          this.isSaveLoading = false
          return false
        }
      })
    },
    saveFormInfo() {
      this.axios({
        method: 'post',
        url: 'api-su/cs/salary/expand/revert',
        data: this.formData,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.dialogVisible = false
            //   this.$nextTick(function() {
            //     this.$refs.pagination.getTableListData();
            //   });
            this.$emit('searchTable')
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    fileChange() {
      var Filedata
      var file
      var fileSize
      Filedata = $('#salaryExcel').val()
      if (!Filedata) {
        return
      }
      try {
        file = $('#salaryExcel')[0].files[0]
        fileSize = (file.size / 1024).toFixed(0)
      } catch (e) {
        this.$message({
          message:
            '您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过10M，建议使用FireFox、Chrome或IE10以上浏览器。',
          type: 'warning',
        })
      }
      // 文件大小和限制类型可以通过子组件传值区分，若不适应于使用页面，可自行判断
      if (this.uploadFile.length == 5) {
        this.$message({
          message: '最多上传5个文件',
          type: 'warning',
        })
        $('#salaryExcel').val('')
        return
      }
      if (fileSize / 1 > 1024 * 5) {
        this.$message({
          message: '最多能上传5M以内的文件',
          type: 'warning',
        })
        $('#salaryExcel').val('')
        return
      }
      if (!/\.(png|jpg|jpeg|PNG|JPG|JPEG)$/.test(Filedata)) {
        this.$message({
          // message: "仅支持上传png、jpg、jpeg格式文件",
          message: '要求格式为JPG、PNG格式，图片大小不超过2M',
          type: 'warning',
        })
        $('#salaryExcel').val('')
        return
      }
      let that = this
      var options = {
        url: common.uploadUrl + 'api-f/files/upload',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
          that.uploadFile.push(data)
          that.srcList.push(data.url)
          that.oldSrcList.push(data.url)
          $('#salaryExcel').val('')
        },
        error: function () {},
      }
      $('#salaryExcelForm').ajaxSubmit(options)
      return false
    },
    delFile(index) {
      this.uploadFile.splice(index, 1)
      this.srcList.splice(index, 1)
      this.oldSrcList.splice(index, 1)
    },
    enlargeImg(index) {
      this.srcList = this.oldSrcList
      var demo = this.srcList
      var frontArr = demo.slice(0, index)
      var behindArr = demo.slice(index, demo.length)
      var list = behindArr.concat(frontArr)
      this.srcList = list
    },
  },
  watch: {
    uploadFile(val) {
      if (val.length > 0) {
        this.$refs.formData.clearValidate('operateVoucher')
      }
    },
  },
}
</script>

<style lang="less" scoped>
.uploadBox {
  position: relative;
  .uploadImg {
    width: 96px;
    height: 36px;
    color: #009588;
    border: 1px solid #009588;
    line-height: 10px;
  }
  .upLoadDom {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    input {
      width: 100px;
      height: 36px;
    }
  }
}
.imgStyle {
  margin-left: 135px;
  li {
    position: relative;
    margin-right: 20px;
    margin-bottom: 20px;
    .iconjian {
      position: absolute;
      right: -6px;
      top: -10px;
      font-size: 20px;
      cursor: pointer;
    }
    .el-image {
      cursor: pointer;
    }
  }
}
</style>
